package com.mllweb.api.core.notice.email;

import com.mllweb.api.core.utils.PropUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

@Component
public class Email {
    @Autowired
    private  Authenticator mailAuthenticator;
    private Properties properties = new Properties();
    private String user;
    private String username;

    public Email() {
        Properties prop = PropUtils.getProperties("email");
        properties.setProperty("mail.smtp.host", prop.getProperty("email.host"));
        properties.put("mail.smtp.auth", prop.getProperty("email.auth"));
        properties.put("mail.transport.protocol", prop.getProperty("email.protocol"));
        this.user= prop.getProperty("email.user");
        this.username= prop.getProperty("email.username");
    }


    public void send(String validateUser, Template template) {

        //  设置对话和邮件服务器进行通讯
        Session session = Session.getDefaultInstance(properties, mailAuthenticator);
        //  设置邮件对象
        Message message = new MimeMessage(session);
        try {
            message.setSentDate(new Date());
            Address address = new InternetAddress(user, username);
            message.setFrom(address);
            Address toAddress = new InternetAddress(validateUser);
            message.setSubject(template.getSubject());
            message.setRecipient(Message.RecipientType.TO, toAddress);
            message.setContent(template.getContent(), template.getContentType());
            message.saveChanges();
//           发送邮件
            System.out.println("doSendHtmlMail() 开始发送邮件……");
            Transport.send(message);
            System.out.println("发送成功！");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("错误！" + e.getMessage());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            System.out.println("错误！" + e.getMessage());
        }

    }
}
